package prog1.common;

import prog1.serialization.ISerializer;
import prog1.serialization.SerializerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Roi
 * Date: 08/12/13
 *
 * This class stores program parameters, allowing serialization/de-serialization to/from parameters file.
 * Serialization / De-serialization is done using "ISerializer" according to "Defs.SERIALIZER_TYPE"
 */
public class Parameters {

    private final ISerializer serializer;
    private final Map<String, String> impl;

    public Parameters() {
        serializer = SerializerFactory.create(Defs.SERIALIZER_TYPE);
        impl = new HashMap<String, String>();
    }

    /**
     * Loads default parameters values
     */
    public void loadDefaults() {
        impl.put("KEY_STORE_TYPE", Defs.Defaults.KEY_STORE_TYPE);
        impl.put("KEY_STORE_PROVIDER", Defs.Defaults.KEY_STORE_PROVIDER);
        impl.put("KEY_STORE_FILE_NAME", Defs.Defaults.KEY_STORE_FILE_NAME);

        impl.put("IV_SIZE_IN_BYTES", String.valueOf(Defs.Defaults.IV_SIZE_IN_BYTES));

        impl.put("FILE_ENCRYPTION_ALGORITHM", Defs.Defaults.FILE_ENCRYPTION_ALGORITHM);
        impl.put("FILE_ENCRYPTION_PROVIDER", Defs.Defaults.FILE_ENCRYPTION_PROVIDER);

        impl.put("KEY_ENCRYPTION_ALGORITHM", Defs.Defaults.KEY_ENCRYPTION_ALGORITHM);
        impl.put("KEY_ENCRYPTION_PROVIDER", Defs.Defaults.KEY_ENCRYPTION_PROVIDER);

        impl.put("FILE_ENCRYPTION_TRANSFORMATION", Defs.Defaults.FILE_ENCRYPTION_TRANSFORMATION);

        impl.put("KEY_STORE_SIGNATURE_ALGORITHM_ALIAS", Defs.Defaults.KEY_STORE_SIGNATURE_ALGORITHM_ALIAS);
        impl.put("KEY_STORE_KEY_ENCRYPTION_ALGORITHM_ALIAS", Defs.Defaults.KEY_STORE_KEY_ENCRYPTION_ALGORITHM_ALIAS);

        impl.put("SIGNATURE_ALGORITHM", Defs.Defaults.SIGNATURE_ALGORITHM);
        impl.put("SIGNATURE_PROVIDER", Defs.Defaults.SIGNATURE_PROVIDER);

        impl.put("INPUT_FILENAME", Defs.Defaults.INPUT_FILENAME);
        impl.put("ENCRYPTED_FILENAME", Defs.Defaults.ENCRYPTED_FILENAME);
        impl.put("DECRYPTED_FILENAME", Defs.Defaults.DECRYPTED_FILENAME);
    }

    /**
     * Adds parameter with name and value
     * @param name parameter name
     * @param value parameter value
     */
    public void add(String name, String value) {
        impl.put(name, value);
    }

    /**
     * Returns parameter value according to its name
     * @param name parameter name
     * @return parameter value
     */
    public String get(String name) {
        return impl.get(name);
    }

    /**
     * Serializes parameters to file
     * @throws Exception
     */
    public void serialize() throws Exception {
        serializer.serialize(impl, Defs.PARAMETERS_FILENAME);
    }

    /**
     * De-serializes parameters from file
     * @throws Exception
     */
    public void deserialize() throws Exception {
        serializer.deserialize(impl, Defs.PARAMETERS_FILENAME);
    }
}
